package cn.touna.jss.modules.third.zhongan;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.factory.RestTemplateConfig;
import cn.touna.jss.common.properties.disconf.ZhonganProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.zhongan.entity.ZhonganRequestEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.utils.ServiceContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import com.zhongan.scorpoin.biz.common.CommonRequest;
import com.zhongan.scorpoin.biz.common.CommonResponse;
import com.zhongan.scorpoin.common.ZhongAnApiClient;
import com.zhongan.scorpoin.common.ZhongAnOpenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;


/**
 * Created by Steve.Tao on 2017/8/16.
 */
@Service
public class ZhonganService {

    @Autowired
    private ZhonganProperties zhonganProperties;

    private static final Logger logger = LoggerFactory.getLogger(ZhonganService.class);

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @ApiMapping(value = "zhongan.authRealIdentity",desc = "众安.征信")
    public Response authRealIdentity(ZhonganRequestEntity.AuthRealIdentityRequest request) {
        request.setRequestNo(TracerContextUtil.getTraceId());
        Response validResponse = ValidUtil.valid(request);
        if (validResponse != null)
            return validResponse;

        JSONObject body = (JSONObject) JSON.toJSON(request);
        body.put("certiNo", request.getIdCard());
        body.remove("idCard");

        JSONObject params = createParams(request.getRequestNo(), "zaedsUserProfileService", "authRealIdentity", body);
        return handleRequest(params);
    }

    private String getProfile() {
        return "prd";
    }

    private Response handleRequest(JSONObject params) {
        logger.info("handleRequest params:{}",params);
        String charset = "UTF-8";
        String signType = "RSA";
        String version = "1.0.0";
        String format = "json";
        String openServiceName = "zhongan.spider.zainfo.zaedsDataOpenService";

        ZhongAnApiClient client =
                new ZhongAnApiClient(getProfile(), zhonganProperties.getAppKey(),
                        zhonganProperties.getPrivateKey(), charset, signType, version, format, restTemplateConfig.getConnectionTimeout(), restTemplateConfig.getReadTimeout());
        try {
            CommonRequest commonRequest = new CommonRequest(openServiceName);
            commonRequest.setParams(params);
            CommonResponse response = (CommonResponse) client.call(commonRequest);
            logger.info("zhongan  result json:{}", response.getBizContent());
            if (!StringUtils.isEmpty(response.getBizContent())) {
                 String rspDataStr = JSONObject.parseObject(response.getBizContent()).getString("rspData");
                JSONObject rspData = JSONObject.parseObject(rspDataStr);
                JSONObject head = rspData.getJSONObject("head");
                String rspCode = rspData.getJSONObject("head").getString("rspCode");
                String result = rspData.getJSONObject("body").getJSONObject("rspInfo").getString("status");
                String msg = rspData.getJSONObject("body").getJSONObject("rspInfo").getString("message");
                if("0000".equals(rspCode)){
                    head.remove("accountNo");
                    head.remove("appKey");
                    head.remove("privateKey");
                    head.remove("requestNo");
                    head.remove("serviceName");
                    head.remove("methodName");

                    if(result != null&& !"SUCC".equals(result)){
                        return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, msg,rspData.toJSONString());
                    }
                    return ResponseFactory.success(rspData);
                }
            }
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL,response.getBizContent());
        } catch (ZhongAnOpenException e) {
            logger.error("调用众安接口异常", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getErrMsg());
        }
    }

    private JSONObject createParams(String requestNo, String serviceName, String methodName, JSONObject body) {
        JSONObject reqData = new JSONObject();

        JSONObject head = new JSONObject();
        head.put("accountNo", zhonganProperties.getAccountNo());
        head.put("appKey", zhonganProperties.getAppKey());
        head.put("privateKey", zhonganProperties.getPrivateKey());
        head.put("requestNo", requestNo);
        head.put("serviceName", serviceName);
        head.put("methodName", methodName);

        reqData.put("head", head);
        reqData.put("body", body);

        JSONObject params = new JSONObject();
        params.put("reqData", reqData);
        return params;
    }

    @ApiMapping(value = "zhongan.riskList",desc = "众安.风险名单")
    public Response riskList(ZhonganRequestEntity.RiskListRequest request) {
        request.setRequestNo(TracerContextUtil.getTraceId());
        Response validResponse = ValidUtil.valid(request);
        if (validResponse != null)
            return validResponse;

        JSONObject body = (JSONObject) JSON.toJSON(request);
        body.put("mobileNo", request.getMobile());
        body.put("idCardNo", request.getIdCard());

        body.remove("mobile");
        body.remove("idCard");

        JSONObject params = createParams(request.getRequestNo(), "zaedsRiskRankService", "queryRankBase", body);
        return handleRequest(params);
    }

    @ApiMapping(value = "zhongan.authCard4Elements",desc = "众安.银联四要素")
    public Response authCard4Elements(ZhonganRequestEntity.AuthCard4ElementsRequest request) {
        Response validResponse = ValidUtil.valid(request);
        if (validResponse != null)
            return validResponse;

        JSONObject body = (JSONObject) JSON.toJSON(request);
        body.put("idCardCore", request.getIdCard());
        body.put("bankPreMobile", request.getMobile());

        body.remove("idCard");
        body.remove("mobile");
        JSONObject params = createParams(ServiceContext.genUniqueId(), "zaedsBankCardService", "authCard4Elements", body);
        return handleRequest(params);
    }

    @ApiMapping(value = "zhongan.assessAddrReliability",desc = "众安.地址可信度")
    public Response assessAddrReliability(ZhonganRequestEntity.AddressRequest request) {
        request.setRequestNo(TracerContextUtil.getTraceId());
        Response validResponse = ValidUtil.valid(request);
        if (validResponse != null)
            return validResponse;JSONObject body = (JSONObject) JSON.toJSON(request);
        String addrArray[] =  request.getAddress().split(",");
        String addrTypeArray[] =  request.getAddressFlag().split(",");

        if(addrArray.length>1  &&  addrTypeArray.length<1){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL,"多地址时,必须传递多个地址类型");
        }
        if(addrTypeArray.length>1  &&  addrArray.length<1){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL,"多地址类型时,必须传递多个地址");
        }

        JSONArray data = new JSONArray();
        boolean flag =false;
        for (int i = 0; i <addrArray.length ; i++) {
        body.put("certiNo", request.getIdCard());
            body.put("address", addrArray[i]);
        body.put("phone", request.getMobile());
            body.put("atype", addrTypeArray[i]+"");
        body.remove("idCard");
        body.remove("mobile");
            JSONObject params = createParams(UUID.randomUUID()+"", "zaedsXmodelService", "assessAddrReliabilityDetail", body);
        Response response = handleRequest(params);
            if(response.getCode().equals("200")){
                flag =true;
                data.add(response.getData());
            }
        }
        if(flag){
            return ResponseFactory.success(data);
        }else{
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, "地址匹配失败");
        }

    }



}
